import 'package:dio/dio.dart';
import 'package:flutter_give/http/print_log_interceptor.dart';
import 'package:flutter_give/http/rsp_instance.dart';

import 'cookie_interceptor.dart';
import 'http_method.dart';

// 封装请求文件
// 统一拦截器在该文件48 - 52行
class DioInstance {
  static DioInstance? _instance;

  DioInstance._();

  static DioInstance instance() {
    return _instance ??= DioInstance._();
  }

  // final Dio _dio = Dio();
  Dio _dio = Dio();

  // 响应默认值
  // required - 必填参数
  // _dio.interceptors - 数组，可以挂载多个拦截器
  final _defaultTime = const Duration(seconds: 30);

  void initDio({
    required String baseUrl,
    String? httpMethod = HttpMethod.GET,
    Duration? connectTimeout,
    Duration? receiveTimeout,
    Duration? sendTimeout,
    ResponseType? responseType = ResponseType.json,
    String? contentType,
  }) {
    _dio.options = BaseOptions(
        method: httpMethod,
        baseUrl: baseUrl,
        // 请求
        connectTimeout: connectTimeout ?? _defaultTime,
        // 响应
        receiveTimeout: receiveTimeout ?? _defaultTime,
        // 发送
        sendTimeout: sendTimeout ?? _defaultTime,
        responseType: responseType,
        contentType: contentType);
    // 请求头拦截器-添加token
    _dio.interceptors.add(CookieInterceptor());
    // 查看请求拦截器-查看特定接口信息
    _dio.interceptors.add(PrintLogInterceptor());
    // 处理登录体系拦截器-处理状态码-全局操作
    _dio.interceptors.add(ResponseInterceptor());
  }

  // cancelToken - 取消接口请求

  ///get请求方式
  Future<Response> get({
    required String path,
    Map<String, dynamic>? param,
    Options? options,
    CancelToken? cancelToken,
  }) async {
    return await _dio.get(path,
        queryParameters: param,
        options: options ??
            Options(
              method: HttpMethod.GET,
              receiveTimeout: _defaultTime,
              sendTimeout: _defaultTime,
            ),
        cancelToken: cancelToken);
  }

  ///post请求方式
  Future<Response> post(
      {required String path,
      Object? data,
      Map<String, dynamic>? queryParameters,
      Options? options,
      CancelToken? cancelToken}) async {
    return await _dio.post(path,
        data: data,
        queryParameters: queryParameters,
        cancelToken: cancelToken,
        options: options ??
            Options(
              method: HttpMethod.POST,
              receiveTimeout: _defaultTime,
              sendTimeout: _defaultTime,
            ));
  }

  // 外部第三方请求
  void changeBaseUrl(String baseUrl){
    _dio.options.baseUrl = baseUrl;
  }
}
